import { IonNav, Platform } from '@ionic/angular';
import { EventService } from 'src/app/shared/service/event.service';
// tslint:disable
import { FormGroup } from '@angular/forms';
import { Injectable, ViewChild, Renderer2 } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';

import * as CryptoJS from 'crypto-js';
import { ToastController, ModalController, NavController, IonTabs, AlertController, MenuController, ActionSheetController, PopoverController } from '@ionic/angular';

import { Subscription } from 'rxjs';
import { Base64ToGallery } from '@ionic-native/base64-to-gallery/ngx';
import { HttpClient } from '@angular/common/http';
import { ComItem } from 'src/app/route/entry/com-item';
declare var wx;
declare var device;
declare const Umeng;
declare const cordova;
declare var JGVerificationPlugin;
//加密
const secretKey = 'axuff_ooiaf_ooieudffaix';
const sKey = 'vmuvjhu_dpey_eabh_opklk';
@Injectable({
  providedIn: 'root'
})

export class AppGlobalService {

  tabsCanGoBack = false;
  tabsParentCanGoBack = false;
  @ViewChild("ionTabs", null) tabs: IonTabs;
  public shareObj: any; // 用于App全局数据共享
  public globalParamNameObj: any;
  globalFormMessageObj: any;
  globalFormCompareObj: any;
  globalSubmitBtnData: any; // 公司认证

  globalHiddenForm: FormGroup; // 公司认证
  globalHiddenMessageObj: FormGroup; // 公司认证
  nextPageFomObj = undefined; // 下一步
  openBackdrop: boolean;
  topTop: boolean;
  wxLoginCode: any; // 小程序进入的code
  wxPayCode = 0; // 微信浏览器支付的code
  debugAppId = 458; // H5 测试环境debugId 检测了地址栏域名
  WebSocketConn: any;
  getSessionPath: any;
  lastMessageIndex: any; // 消息模块记录上次选中
  invitationMsgBdge: boolean; // 铺铺旺邀约聊天红点是否显示 false：不显示。
  backButtonPressed = false; // 是否连续两次按返回按钮
  isShowInquiryPageModal: boolean;
  fengwoWechatMiniProgrameId = 'gh_1c97d5418ff1'; // 蜂喔用户端小程序原始ID 
  ReleaseVersionCode = 2054; // pxw750 ppw411 js2052-453 lj_3032-452 
  appVersion = '2.4.2'; // pxw'7.5.3' ppw 3.13 lj 2.3.01 js 2.3.11;
  clientType = 'js'; // 铺铺旺 ppw 铺小旺 pxw  蜂喔 lj  蜂喔商户 js
  pushAlias = "js_p_"; // 铺铺旺ppw_p_ 铺小旺pxw_p_ 蜂喔lj_p_ 蜂喔商户js_p_
  globalSubscription: Subscription;
  needClearGlobalSubscription = true;
  needAutoChoosenTab = false;
  tab5Subscription: Subscription;
  globalMobileUUIDArray = [];
  globalHeadPicUrlUUIDArray = [];
  globalonLineChatUUIDArray = [];
  globalcallBtnUUIDArray = [];
  globalPhoneTagDataArray = [];
  scResult: any = { showName: "", filter: {}, order: {} };
  scListTagName: any;
  fingerPrintParams: any;// 指纹登录用到的认证参数
  fingerPrintSubmitId: any;// 指纹登录用的submitId
  submitShowName: any;// 指纹登录用的submitId
  isInstallBaiduMapApp = '0';// 是否安装了百度地图index 0
  isInstallTencentMapApp = '0';// 是否安装了腾讯地图index 1
  isInstallGaoDeMapApp = '0';// 是否安装了高德地图index 2
  lastTime = 0;
  lastPageTime = 0;
  isMiniProgram = false;
  // 只有在安卓QQ内打开H5才有个这个问题
  isH5OpenInQQ = window.navigator.userAgent.match(/QQTheme/) && window.navigator.userAgent.match(/Android/);
  // switchBlockWithCommonFilterResult: any;
  // defaultCityId = 1101;
  // defaultCityName = '北京';
  // defaultCityCenter = { lng: 116.402544, lat: 39.908958 }; // 北京中心点 { lng: 116.402544, lat: 39.908958 };
  defaultCityId = 4403;
  defaultDistrictCode = 440304;
  defaultCityName = '深圳';
  defaultDistrictName = '福田区';
  reportPageId = 0;
  defaultCityCenter = { lng: 114.06450485520935, lat: 22.549179943799096 }; // 北京中心点 { lng: 116.402544, lat: 39.908958 };
  alertDiv: any;
  alertDivTotalCount: any;
  tipsDiv: any; // 详情返回提示用
  tipsTotalCount: any;
  isPreview = false; // 是预览？
  baiduNavigationAPI = "https://api.map.baidu.com/marker";
  ngZorroTabCurrentTabIndex = 0;
  footerButton: any; //  蜂喔赚钱宝 1.6.14 新增底部按钮
  headerTipTag: any; //  蜂喔赚钱宝 1.6.14 新增顶部提示按钮
  headerSiftTag: any; //  蜂喔赚钱宝 1.6.14 新增顶部筛选按钮
  headerTopTab: any; //  蜂喔赚钱宝 1.6.14 新增顶部切换tab
  headerTopTabIndex = 0; //  蜂喔赚钱宝 1.6.14 新增顶部切换tab
  tmpParams: any;// 1.6.14 新增需求 指定分享对象参数  
  numberOfRedDotMessage = 0; //1.6.15 红点消息数量
  recommendTab: 0; //1.9.20 蜂喔推荐tab
  isVisitor = false;// 是否为访客
  nowDate = Date.now();
  visitorMsg: any// 是否为访客


  // 1.6.15 蜂喔商户
  isShowMessageNotifyDiv = false;
  showMessageBody = ''; // 消息内容
  showMessageDateTime = ''; // 消息时间
  // 1.9.18 蜂喔用户新增属性
  needHiddenId = '';
  serviceLink: any;
  // 1.9.19 蜂喔用户 找阿姨 -》 家电清洗 -》 立即下单 选择规格更新价格的按钮
  priceBtns: any;
  // 1.9.20 蜂喔用户 确认订单 -》 商品总价 -》 提交订单
  orderTotalAmount: any;
  orderRealPayAmount = 0;//实收金额
  // 1.9.20 蜂喔用户 申请开票 -》 商品总价 -》 总可开票金额
  invoiceTotalAmount = 0;
  // 1.9.20 蜂喔用户 申请开票 -》 商品总价 -》 订单号
  invoiceOrderNo: any;
  // 1.9.20 蜂喔用户 申请开票 -》 商品总价 -》 店铺Id
  invoiceStoreId: any;
  // 1.9.20 蜂喔用户新增结余尾款
  balancePayment = 0;
  // 2.0.0 蜂喔用户 购物车列表id
  shoppingCarId = "";
  balancePaymentArray: any;
  balancePaymentChecked = false;
  balancePaymentCheckedCount = 0;
  // 1.9.20 登录状态 需支付订单浮窗处理等
  loginStatus = false;
  // 1.9.22 选择地址 id
  needAppendAddressId = false;
  shopAddressSelectItemId = '';
  itemKeyName = 'shop_ship_address_id';
  shopAddressSelectItemLocation = '';
  shopAddressSelectItemPhone = '';
  shopAddressSelectItemName = '';
  addressEventResultValue = ''; // 2.2.2 shopAddressEventResultValue
  addressEventResultName = ''; //2.2.2 shopAddressEventResultName
  // 1.6.33 套餐商品列表加入购物车
  shopGoodsSecondGlobalCountLabel = '';
  // 1.6.34 新增inviteBtn
  inviteBtn: any;
  // 点击的商品的下标
  shopGoodsSecondGlobalClickIndex: any;
  // 1.6.34 新增标志位用于记录上一次点击的切换店铺
  switchShopUniqueId = '';
  switchServiceCenterUniqueId = '';
  currentNickName = '';
  currentAvatarUrl = 'assets/img/head.png';
  homePageToTop = false;
  homePageScrollTop: any;
  itemTabId: any;
  // 用户端添加购物车登陆之后是否需要刷新
  disableRefreshAfterLogin = '';
  sendLabelMsg: any;
  noneFirstEmployeList = false;
  dynamicDetailsData: any;
  videoDetailsData: any;
  shellData: any = {};
  // 服务中心新增按钮
  msgTopTipButtonObj: any;
  msgFirstTipObj: any;
  msgSecondTipObj: any;
  privateRightPageLink = null;
  // 土特左下角购物车按钮
  floatShoppingCartIsShow = false;
  // 商户端 求助帮助页面 第x条动态的下标
  commentsListIndex = '';
  floatShoppingCartObj: any;
  loginRes: any;
  // 标识  储存商户端给客户下单页面需要的地址id
  needShopShipAddressId = false;

  // 2024.01.24 新增安卓应用商店权限提示
  callNumberTipsHeader = "蜂喔需要申请获取您的拨打电话权限";
  callNumberTipsContent = "使用拨打电话功能是为了方便您联系客服";

  public iconTabsCssStyle = '';
  private db;
  public fromH5forRecord: any;// 是否是从H5分享链接新增的，如果URL带了这个参数且为true则记录用于submit接口提交。 2023-07-31

  public homePageId = '';

  public pageDisabledBoxCssStyle = 'margin-top:2.75rem;'; //默认值可以配置

  public privatePolicyLink = 'https://pay.fengwo168.com/staticH5/fengwo.html?hiddenTtitle=true'; // 2023-09-05 隐私权限协议
  public serviceAgreementLink = 'https://pay.fengwo168.com/staticH5/serviceAgreement.html?hiddenTtitle=true'; // 2023-09-05 服务协议
  public settleInLink = 'https://pay.fengwo168.com/staticH5/fengwoPlatformEntryAgreement.html'; // 2024-03-05 入驻协议
  selectAddressList = '';// 四级地址选择数组
  formChecked = false // 表单已经校验过
  chatGroupNo = '';// 2023.12.02 
  callBackFunctionOnEnterGroup: any;


  // 去结算购物车数量 2024.04.09 2.2.19 
  modalCartNum = 0;
  settleCartPrice = 0.0;
  settleCartIds = new Set(); // 存储购物车ID


  callBackFunctionOnGetAddressByPoint: any; // 通过经纬度获取地址名称
  getAddressLng: any; // Lng
  getAddressLat: any; // Lat
  searchShopLng: any;
  searchShopLat: any;

  needCheckTabName: any;

  setCustomBoxVisibility: any; // 全选按钮状态
  updateImageSubmit: any; // 2.2.20 新增上传图片用的按钮事件
  isUploadImgComplete = false; // 2.2.20 新增参数用于点击微信分享时检查是否上传图片完成。

  partnerApplySearchAreaPageId: 0; // 2.3.0 新增搜索百度地图时使用我们自己的数据源
  loadSharePicCallBack: any; // 2.3.0 新增加载图片回调
  disableConsoleLog = false; // 2024.07.03 支持配置关闭控制台日志
  hiddenAddBtn: any; // 2024.07.04 支持配置聊天隐藏按钮
  locationAddressLabel = '';
  loadSwitchBtnPicCallBack = (obj) => { }; // 2.3.4 新增加载图片回调
  loadFixedTabCallBack = (obj) => { }; // 2.3.4 新增加载图片回调
  private refreshDataTime = 0;
  refreshDelayTime = 0;
  checkIsApp = localStorage.getItem('client') && localStorage.getItem('client') === 'APP';

  currentPartParams = {}; // 2024.09.24 新增part参数
  coms: ComItem[];
  pageId: "";  

  enableDouyinShare = true;//12.06 默认打开抖音分享


  pullToRefresh = (event) => {
    if (event) {
      event.target.complete();
    }
    const nowTime = new Date().getTime() / 1000; // 指定毫秒数内不刷新
    if (nowTime - this.refreshDataTime > this.refreshDelayTime) {

      // 当前是在首页并且开启了开关
      // 配置了下拉刷新首页就只刷首页
      const currentPath = localStorage.getItem("tabPath");
      if (currentPath !== null && currentPath === 'home/tab1' && this.refreshHomePageEnabled) {
        // 配置了下拉刷新子选项卡好货，店铺，商机，服务，活动就只刷新子选项卡
        this.eventService.eventEmit.emit('pulltoRefreshHomePage', '1');
        this.consoleLog('下拉刷新首页', '');

      } else {
        // 配置了下拉刷新子选项卡好货，店铺，商机，服务，活动就只刷新子选项卡
        this.eventService.eventEmit.emit('checkListIsShowRefresher', '1');
        this.consoleLog('下拉刷新子选项卡', '');
      }

    }

  }; // 2.3.4 新增加载图片回调
  loadImgPicCallBack = (obj) => { this.eventService.eventEmit.emit("loadImgPicCallBack", obj) }; // 2.3.5 新增加载图片回调
  addedMessages = new Set();  // 2024.08.05  用于存储已经添加的消息的createTime

  addedFormatTimes = new Set();
  defaultImg = 'https://zeno-img.oss-cn-shenzhen.aliyuncs.com/file_1723258329829fbde0af09db1d9287fd2f7d873ed5e0d.png';

  totalFileUploadingNum = 0;// 2024.11.01 上传文件总进度

  uploadVideCompletedCallBack = (obj) => { }; // 2024.11.01 上传视频完成回调

  refreshHomePageEnabled = false;// 2024.11.20 新增支持刷新首页
  targetObj: { pageId: any; params: any; sessionId: string; };
  popUpLoginLink = null; // 12.09 2.4.1 新增弹窗

  constructor(
    public toastController: ToastController,
    public router: Router,
    private route: ActivatedRoute,
    public nav: NavController,
    public modalController: ModalController,
    public alertCtrl: AlertController,
    public menuCtrl: MenuController,
    public actionSheetCtrl: ActionSheetController,
    public popoverCtrl: PopoverController,
    public eventService: EventService,
    private platform: Platform,
    public base64ToGallery: Base64ToGallery,
    private http: HttpClient,
  ) {
    this.shareObj = {};
    this.globalParamNameObj = {};
    this.globalFormMessageObj = {};
    this.globalFormCompareObj = {};
    this.openBackdrop = false;
    this.topTop = false;
    this.isShowInquiryPageModal = true;
    this.initCacheDb();
    this.initData();
  }

  setOpenBackdrop(b) {
    this.openBackdrop = b;

  }

  // 线上项目预览,测试环境项目预览,apk 则显示按钮 其他情况如H5,不显示
  checkIsPreviewAndIsApp() {
    return this.isPreview || (localStorage.getItem('client') && localStorage.getItem('client') === 'APP');
  }


  // 检查是否是 线上项目预览,测试环境项目预览,H5
  checkIsPreviewAndIsNotApp() {
    return this.isPreview || (localStorage.getItem('client') && localStorage.getItem('client') !== 'APP');
  }

  /**
   * 取出当前参数
   */
  getCurrentTarget() {
    try {
      const targetObj = JSON.parse(localStorage.getItem('targetObj'));
      if (targetObj && targetObj.bat && targetObj.bat.length > 0) {
        targetObj.forward = targetObj.bat[targetObj.bat.length - 1];
        console.log('当前page------> targetObj.forward:', targetObj.forward);
        return targetObj.forward;
      } else {
        console.log('当前page------> targetObj is null');
        if (targetObj) {
          targetObj.forward = null;
        }
        localStorage.removeItem('targetObj');
        return null;
      }
    } catch (error) {
      console.log('当前page------> error ' + JSON.stringify(error));
    }

  }
  /**
   * 退出一个历史参数
   */
  popTarget(index?) {
    const targetObj = JSON.parse(localStorage.getItem('targetObj'));
    if (targetObj && targetObj.bat && targetObj.bat.length > 0) {
      targetObj.bat.pop();
      if (targetObj.bat.length > 0) {
        targetObj.forward = targetObj.bat[targetObj.bat.length - 1];
        localStorage.setItem('targetObj', JSON.stringify(targetObj));
        console.log('当前page------> targetObj.forward:', targetObj.forward);
        return targetObj.forward;
      } else {
        console.log('当前page------> targetObj is null');
        targetObj.forward = undefined;
        localStorage.removeItem('targetObj');
        return undefined;
      }
    } else {
      console.log('当前page------> targetObj is null');
      localStorage.setItem('targetObj', JSON.stringify(targetObj));
      return undefined;
    }
  }

  /**
   * 退出All历史参数
   */
  popAllTarget() {
    localStorage.removeItem('targetObj');
    console.log('回到Tab时清空历史targetObj');
  }
  /**
   * 显示提示信息
   *
   * @param {string} message 提示信息
   * @param {number} [duration=2000] 持续时间
   * @param {('top' | 'bottom' | 'middle')} position 显示位置
   * @memberof AppGlobalService
   */
  async showToast(message: string, duration: number = 2000, position: 'top' | 'bottom' | 'middle', buttonIcon?) {

    if (message !== null && message !== '操作成功！') {

      let toast;
      if (buttonIcon !== undefined) {
        toast = await this.toastController.create({
          message,
          duration,
          buttons: [
            {
              side: 'start',
              icon: buttonIcon ? buttonIcon : 'assets/icon/success.svg',
              text: '',
              handler: () => {
              }
            }
          ],
          position,
          cssClass: 'error'
        });
      } else {
        toast = await this.toastController.create({
          message,
          duration,
          position,
          cssClass: 'error'
        });
      }
      toast.present();
    }

  }

  /**
   * 储存跳转信息
   * @param {object} forwardObj 提示信息
   * @memberof AppGlobalService
   */
  async goToForward(forwardObj: any) {

    // 2024.07.08 检查配置是否需要跳转到H5对应的页面
    if (forwardObj.params.jumpTargetInH5Browser
      && forwardObj.params.jumpTargetInH5Browser !== '0') {
      if (localStorage.getItem('client')
        && localStorage.getItem('client') !== 'APP') {
        forwardObj.pageId = forwardObj.params.jumpTargetInH5Browser;
      }
    }
    if (forwardObj.params.jumpTargetInAPP
      && forwardObj.params.jumpTargetInAPP !== '0') {
      if (localStorage.getItem('client')
        && localStorage.getItem('client') === 'APP') {
        forwardObj.pageId = forwardObj.params.jumpTargetInAPP;
      }
    }

    // 2024.03.14 
    // 跳转到扫描二维码
    if (forwardObj.params.qrCodeScanner !== undefined && forwardObj.params.qrCodeScanner == 'true') {
      console.log('qr-code-scanner id defined!');
      this.router.navigate(['qr-code-scanner'], { queryParams: { params: JSON.stringify(forwardObj.params) } });
      return;
    }

    // 处理包含登录的参数
    if (forwardObj.params.visitor === undefined && localStorage.getItem('loginStatus') !== 'true' && forwardObj && forwardObj.params !== undefined && forwardObj.params.oneLogin !== undefined && forwardObj.params.passwordLogin !== undefined) {
      if (forwardObj.params.disableClick !== undefined) {
        return;
      }
      // 包含登录参数 先登录
      let link: any = {};
      link['params'] = forwardObj.params;
      if (forwardObj.viewId !== undefined) {
        link['viewId'] = forwardObj.viewId;
        link['type'] = 'view'
      } else if (forwardObj.pageId !== undefined) {
        link['pageId'] = forwardObj.pageId;
        link['type'] = 'page'
      }
      this.eventService.emit('openPage', JSON.stringify(link));
      return
    }

    let position = JSON.parse(localStorage.getItem("position"));

    this.needClearGlobalSubscription = false;
    this.openBackdrop = false;
    let targetObj;
    // 跳转页面前清除modal
    const modal = await this.modalController.getTop();
    if (modal && modal.innerText.lastIndexOf('欢迎下载并使用蜂喔商户') === -1 && modal.innerText.lastIndexOf('我们需要获得您的手机设备信息') === -1) {
      modal.dismiss();
    }

    if (localStorage.getItem('targetObj') && localStorage.getItem('targetObj') !== 'null') {
      targetObj = JSON.parse(localStorage.getItem('targetObj'));
    } else {
      targetObj = {
        forward: { params: {} },
        path: '',
        bat: []
      };
      // Variable.getInstance().targetObject;
    }
    targetObj.forward = forwardObj;
    const currentPath = window.location.href;
    console.log('currentPath------> ', currentPath);
    const urlArray = currentPath.split('/');
    const pageUrl = urlArray[urlArray.length - 1];
    const page = pageUrl.split('?')[0];
    const tabPages = [
      'tab1',
      'tab2',
      'tab3',
      'tab4',
      'tab5',
    ];
    let nextPath = '';

    if (tabPages.indexOf(page) > -1) {
      nextPath = 'nav1';
      if (!localStorage.getItem('lastNavIndex')) {
        localStorage.setItem('lastNavIndex', '1');
      }
    } else if (page === 'details') {

      if (!localStorage.getItem('tabPath')) {
        localStorage.setItem('tabPath', 'home/tab1');
      }
      const index = + localStorage.getItem('lastNavIndex') !== null ? + localStorage.getItem('lastNavIndex') + 1 : 1;
      nextPath = '/nav' + index;
    } else if (page === 'return_url') {

      const index = + localStorage.getItem('lastNavIndex') !== null ? + localStorage.getItem('lastNavIndex') + 1 : 1;
      nextPath = '/nav' + index;
    } else if (page === 'navSearch') {

      const index = + localStorage.getItem('lastNavIndex') !== null ? + localStorage.getItem('lastNavIndex') + 1 : 1;
      nextPath = '/nav' + index;
    } else if (page === 'chatOnline') {

      const index = + localStorage.getItem('lastNavIndex') !== null ? + localStorage.getItem('lastNavIndex') + 1 : 1;
      nextPath = '/nav' + index;
    } else if (page === 'newShop') {
      localStorage.setItem('backToNewShop', 'true');
      const index = + localStorage.getItem('lastNavIndex') !== null ? + localStorage.getItem('lastNavIndex') + 1 : 1;
      nextPath = '/nav' + index;
    } else if (page === 'laijianLogin') {
      localStorage.setItem('backToLaiJianLogin', 'true');
      const index = + localStorage.getItem('lastNavIndex') !== null ? + localStorage.getItem('lastNavIndex') + 1 : 1;
      nextPath = '/nav' + index;
    } else {
      const index = + page.substring(3) + 1;
      localStorage.setItem('lastNavIndex', index.toString());
      nextPath = '/nav' + index;
      if (index > 21) {
        nextPath = localStorage.getItem('tabPath');
        console.log('nextPath------> too deep !!!!!!!!\n', nextPath);
        localStorage.removeItem('lastNavIndex');
      }

    }
    // nextPath = 'nav';
    console.log('nextPath------> ', nextPath);
    targetObj.path = nextPath;

    targetObj.bat.push(forwardObj);
    // 修改上一个请求的参数 cuttab 记住上次tab项
    if (targetObj.bat.length > 1 && forwardObj.params && forwardObj.params.cuttab) {
      const lastForwardObj = targetObj.bat[targetObj.bat.length - 2];
      if (lastForwardObj.params.cuttab) {
        lastForwardObj.params.cuttab = forwardObj.params.cuttab;
      }
    }

    // 蜂喔2.2.8 2023年9月22日新增用于计算districtCode
    if (forwardObj.params && forwardObj.params.calculateDistrictCode !== undefined) {
      let position = JSON.parse(localStorage.getItem("position"));
      if (position && position.districtCode) {
        console.log(new Date().toLocaleString() + '.' + new Date().getMilliseconds() + '  posi.districtCode', '  	   ');
        forwardObj.params.calculateDistrictCode = position.districtCode;
      } else {
        console.log(new Date().toLocaleString() + '.' + new Date().getMilliseconds() + '  default.districtCode', '  	   ');
        forwardObj.params.calculateDistrictCode = this.defaultDistrictCode;
      }
    }

    //todo 蜂喔1.9.0 新需求 如果跳转页面带了经纬度则需要使用手机定位存储的经纬度
    if (forwardObj.params
      && forwardObj.params.latitude
      && forwardObj.params.longitude
      && forwardObj.params.disablePoints === undefined
    ) {
      if (forwardObj.params.useParamsPoints === undefined) {
        if (localStorage.getItem("position")) {
          let position = JSON.parse(localStorage.getItem("position"));

          if (forwardObj.params.useCurrentPosition !== undefined) {
            position = JSON.parse(localStorage.getItem("currentCityPosition"));
          }

          if (position.center && position.center.lat && position.center.lng) {
            forwardObj.params.latitude = position.center.lat;
            forwardObj.params.longitude = position.center.lng;
          }
          if (position.center.name && position.center.code) {
            forwardObj.params.cityName = position.center.name;
            forwardObj.params.cityCode = position.center.code;
          }
        }
      }
    }





    // todo 2.2.2 是否需要带location参数
    if (forwardObj.params && forwardObj.params.needUseMapLocation) {
      if (localStorage.getItem("mapPosition")) {
        const position = JSON.parse(localStorage.getItem("mapPosition"));
        if (position) {
          targetObj.forward.params['location'] = { latitude: 0.0, longitude: 0.0 };
          targetObj.forward.params['location'].latitude = position.center.lat;
          targetObj.forward.params['location'].longitude = position.center.lng;
        }
      }
    }

    // 2.2.20 新增配置参数用于设置默认值
    if (forwardObj.params
      && forwardObj.params.settingAGSName
    ) {
      if (!forwardObj.params.settingAGSValue) {
        this[forwardObj.params.settingAGSName] = null;
      } else {
        this[forwardObj.params.settingAGSName] = forwardObj.params.settingAGSValue;
      }
    }

    // 2024.10.29 for /home api
    if (forwardObj.params
      && forwardObj.params.settingAGSName1
    ) {
      if (!forwardObj.params.settingAGSValue1) {
        this[forwardObj.params.settingAGSName1] = null;
      } else {
        this[forwardObj.params.settingAGSName1] = forwardObj.params.settingAGSValue1;
      }
    }


    // localStorage.setItem('targetObj', JSON.stringify(targetObj));

    // TODO 跳转到设置页面没有请求
    // if (forwardObj.params && !forwardObj.params.homeRecommendTabIndex) {
    //   setTimeout(() => {
    //     if (forwardObj.params.indexTab) {
    //       localStorage.setItem("indexTab", forwardObj.params.indexTab);
    //       const tabIndex = parseInt(forwardObj.params.indexTab);
    //       this.eventService.eventEmit.emit("topTabChangeByIndex", tabIndex);
    //       if (forwardObj.params.subTab_index) {
    //         localStorage.setItem('subTab_index', forwardObj.params.subTab_index);
    //       }
    //       //1.9.20 蜂喔推荐tab
    //       if (forwardObj.params.recommendTab) {
    //         this.recommendTab = forwardObj.params.recommendTab;
    //       }
    //     }
    //   }, 100);
    // }


    // ngzorro tab 切换
    if (forwardObj.params && forwardObj.params.publishTabIndex) {
      localStorage.setItem("publishTabIndex", forwardObj.params.publishTabIndex);
      localStorage.removeItem("needRefreshTab3");
      if (forwardObj.params.tabIndex) {
        const tabId = 'tab' + forwardObj.params.tabIndex + 'MainPageTop' + forwardObj.params.publishTabIndex;
        setTimeout(() => {
          if (document.getElementById(tabId)) {
            document.getElementById(tabId).click();
          }
        }, 200);
      }
    }

    // if (forwardObj.params.tabIndex !== undefined) {
    //   forwardObj.params.tabIndex = null;
    // }
    if (localStorage.getItem('needLoginToRefreshPage') === "true" && localStorage.getItem('loginStatus') === "true") {
      this.popTarget();
      localStorage.setItem("needRefresh", "true")
      this.goBack();

      localStorage.removeItem('needLoginToRefreshPage')
      forwardObj.params.tabIndex ? delete forwardObj.params.tabIndex : ""
      return;
    }
    // 软切换tab1-5
    if (forwardObj.params && forwardObj.params.tabIndex) {
      // 清除访问历史
      if (forwardObj.params.homeRecommendTabIndex) {
        const path = 'home/' + 'tab' + forwardObj.params.tabIndex.toString();
        forwardObj.paramsStr = JSON.stringify(forwardObj.params);
        this.router.navigate([path], { queryParams: forwardObj });
      } else {
        console.log(new Date().toLocaleString() + '.' + new Date().getMilliseconds() + '  	   ', forwardObj);
        // 2.2.3 新增登录成功页面跳转
        if (forwardObj.params && forwardObj.params.afterOpenLoginSuccessPage) {

          let tempTarget = Object.assign({}, forwardObj);
          setTimeout(() => {

            console.log('begin to forwardTarget------------------------------------');
            let tempReplaceUrl: any;
            if (tempTarget.params && tempTarget.params.replace) {
              tempReplaceUrl = tempTarget.params.replace === 'replace';
            }

            if (this.homePageId !== '' && tempTarget.pageId === this.homePageId) {
              return;
            }
            if (tempTarget.params && tempTarget.params.tabIndex) {
              tempTarget.params.tabIndex = undefined;
            }
            // 已经登录成功且入口为H5且是details路由则加个标记
            if (localStorage.getItem('detailPageFromH5')) {
              tempTarget['detailPageFromH5'] = true;
            }

            this.goToForward(tempTarget);
          }, 50);
          const path = 'home/' + 'tab' + forwardObj.params.tabIndex.toString();
          forwardObj.paramsStr = JSON.stringify(forwardObj.params);
          this.router.navigate([path], { queryParams: forwardObj });
        } else {
          const count = +localStorage.getItem('lastNavIndex') - 1;
          if (count > 0) {
            this.popAllTarget();
            // 1.9.0 改动5 配置 
            // if (forwardObj.params && forwardObj.params.back_target !== undefined) {
            //   this.appGlobalService.goBack();
            // } else {
            history.go(-count);
            setTimeout(() => {
              localStorage.setItem("needRefreshTab1", "true");
              localStorage.setItem("needRefreshTab2", "true");
              localStorage.setItem("needRefreshTab3", "true");
              localStorage.setItem("needRefreshTab4", "true");
              localStorage.setItem("needRefreshTab5", "true");
              const path = 'home/' + 'tab' + forwardObj.params.tabIndex.toString();
              // add by andrew 发现一个bug从tag传过来的参数只能转string不能转obj
              forwardObj.paramsStr = JSON.stringify(forwardObj.params);
              this.router.navigate([path], { queryParams: forwardObj });
            }, 100);
            // }
            console.log(new Date().toLocaleString() + '.' + new Date().getMilliseconds() + '  	   ', forwardObj);
          } else {
            const path = 'home/' + 'tab' + forwardObj.params.tabIndex.toString();
            forwardObj.paramsStr = JSON.stringify(forwardObj.params);
            this.router.navigate([path], { queryParams: forwardObj });
          }
        }


      }
    } else {
      // 蜂喔·蜂喔商户新增了两个 路由 "/laijianLogin" 、"/newShop"
      if (forwardObj.params && forwardObj.params.path === '/laijianLogin') {

        this.router.navigate([forwardObj.params.path], { queryParams: { item: JSON.stringify(forwardObj) } });
      } else {
        if (forwardObj.params && forwardObj.params.back_target && forwardObj.pageId === forwardObj.params.back_target) {

          this.router.navigate([targetObj.path], { queryParams: forwardObj, replaceUrl: true });
          const tab = localStorage.getItem('tab');
          const index = tab[tab.length - 1, 1];
          localStorage.removeItem('needRefreshTab' + index);

        } else {
          let tempReplaceUrl: any;
          if (forwardObj.params && forwardObj.params.replace) {
            tempReplaceUrl = forwardObj.params.replace === 'replace';
          }

          if (tempReplaceUrl && targetObj.path !== 'nav1') {
            if (targetObj && targetObj.bat && targetObj.bat.length > 1) {
              targetObj.bat.splice(targetObj.bat.length - 2, 1);

            }
          }

          //2024.02.29 修复H5访问异常
          if (targetObj.forward.detailPageFromH5 !== undefined) {
            targetObj.path = 'nav2';
          }

          // 2024.07.12 防止跳转异常
          if (targetObj.path === '/navNaN') {
            if (targetObj.bat && targetObj.bat.length > 0) {
              const batLen = targetObj.bat.length;
              targetObj.path = '/nav' + (parseInt(batLen, 10) + 1)
            }
          }
          this.router.navigate([targetObj.path], { queryParams: forwardObj, replaceUrl: tempReplaceUrl });
        }

      }
    }
    localStorage.setItem('targetObj', JSON.stringify(targetObj));
    console.log('global.service----->', JSON.stringify(targetObj.path), JSON.stringify(forwardObj));


  }
  /**
   * 跳转到指定的URL
   */

  openUrl(title, url, target = "0", params = {}) {
    // 小程序暂不支持
    if (url.indexOf('https://yun.kujiale.com') > -1 && localStorage.getItem('client') === 'JSAPI') {
      this.showToast('抱歉暂不支持查看，请使用蜂喔APP查看', 1500, 'middle');

    } else {
      if (url.indexOf('http') > -1) {
        const path = '/navUrl';
        this.router.navigate([path], { queryParams: { url, title: (title ? title : ""), target, params } });
      } else {
        this.showToast('抱歉出错了，请稍后再试试', 1500, 'middle');
      }

    }
  }

  /**
  * 跳转到指定的URL
  */

  openUrl2(title, url, shareBtn) {
    // 小程序暂不支持
    if (url.indexOf('https://yun.kujiale.com') > -1 && localStorage.getItem('client') === 'JSAPI') {
      this.showToast('抱歉暂不支持查看，请使用蜂喔APP查看', 1500, 'middle');

    } else {
      if (url.indexOf('http') > -1) {
        const param = {};
        const path = '/navUrl';
        this.router.navigate([path], {
          queryParams: {
            url, title: (title ? title : ""), target: "0", param,
            shareTarget: shareBtn.link.target,
            shareName: shareBtn.link.params.name,
            shareCity: shareBtn.link.params.city,
            sharePhone: shareBtn.link.params.phone,
            opportunity_id: shareBtn.link.params.opportunity_id ? shareBtn.link.params.opportunity_id : '',
            plugin_id: shareBtn.link.params.plugin_id ? shareBtn.link.params.plugin_id : '',
            share: shareBtn.link.params.share
          }
        });
      } else {
        this.showToast('抱歉出错了，请稍后再试试', 1500, 'middle');
      }

    }
  }

  // 获取当前时间
  getNowFormatDate() {
    const date = new Date();
    let year = date.getFullYear();
    let month = String(date.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的  
    let day = String(date.getDate()).padStart(2, '0');
    let hour = String(date.getHours()).padStart(2, '0');
    let minute = String(date.getMinutes()).padStart(2, '0');
    let second = String(date.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
  }

  // 获取当前时间
  getNowFormatDateYYYYMMDDHHMM(dateStr?) {
    let date = new Date();
    if (dateStr !== undefined) {
      date = new Date(dateStr);
    }
    const seperator1 = "-";
    const seperator2 = ":";
    const month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
    const strDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
    const strHour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
    const strMinu = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
    const currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
      + " " + strHour + seperator2 + strMinu;
    return currentdate;
  }
  // 获取当前时间
  getNowFormatDateYYYYMMDD(yearNum?) {
    const date = new Date();
    const seperator1 = "-";
    const seperator2 = ":";
    const month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
    const strDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
    const strHour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
    const strMinu = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
    let fullYear = date.getFullYear();
    if (yearNum !== undefined) {
      fullYear = fullYear - yearNum;
    }
    const currentdate = fullYear + seperator1 + month + seperator1 + strDate;
    return currentdate;
  }

  // 获取当前时间 之前的第n天
  getNowFormatDateYYYYMMDD2(day?) {
    let date = new Date();
    if (day !== undefined) {
      date.setDate((date.getDate() + 1) - Number(day));
    }
    const seperator1 = "-";
    const seperator2 = ":";
    const month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
    const strDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
    const strHour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
    const strMinu = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
    let fullYear = date.getFullYear();
    const currentdate = fullYear + seperator1 + month + seperator1 + strDate;
    return currentdate;
  }

  getNowFormatDateHHMM() {
    const date = new Date();
    const strHour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
    const strMinu = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
    const currentdate = strHour + ":" + strMinu;
    return currentdate;
  }

  getFormGroupWithParamName(paramName) {
    if (!this.globalParamNameObj[paramName]) {
      this.globalParamNameObj[paramName] = new FormGroup({});
    }
    return this.globalParamNameObj[paramName];
  }

  resetFormGroupWithParamName(paramName) {
    if (this.globalParamNameObj[paramName]) {
      const formGroup: FormGroup = this.globalParamNameObj[paramName];
      formGroup.reset();
      return formGroup;
    }
  }

  delFormGroupWithParamName(paramName) {
    if (this.globalParamNameObj[paramName]) {
      delete this.globalParamNameObj[paramName];
    }
  }
  delAllFormGroup() {
    this.globalParamNameObj = {};
    this.nextPageFomObj = undefined;
  }

  setFormGroupMessageWithParamName(paramName, messageObj) {
    this.globalFormMessageObj[paramName] = messageObj;
  }
  getFormGroupMessageWithParamName(paramName) {
    if (this.globalFormMessageObj[paramName]) {
      return this.globalFormMessageObj[paramName];
    } else {
      return '';
    }

  }

  delAllFormGroupMessage() {
    this.globalFormMessageObj = {};
  }
  setFormCompareWithParamName(paramName, compareObj) {
    this.globalFormCompareObj[paramName] = compareObj;
  }
  getFormCompareWithParamName(paramName) {
    if (this.globalFormCompareObj[paramName]) {
      return this.globalFormCompareObj[paramName];
    } else {
      return [];
    }
  }

  delFormCompareWithParamName(paramName) {
    if (this.globalFormCompareObj[paramName]) {
      delete this.globalFormCompareObj[paramName];
    }
  }
  delAllFormCompare() {
    this.globalFormCompareObj = {};
  }

  getShareWithKey(key) {
    return this.globalParamNameObj[key];
  }

  setShareWithParamName(key, obj) {
    this.shareObj[key] = obj
  }

  // 判断是否为手机号的正则表达式
  isPhone(phones) {
    const myreg: RegExp = /^[1][3,4,5,7,8,9][0-9]{9}$/;
    if (!myreg.test(phones)) {
      console.log('手机号格式不正确');
      return false;
    } else {
      console.log('手机号格式正确');
      return true;
    }
  }


  openPage(link, title?) {
    if (!link) {
      return;
    } else if (link.type === 'tip' && link.params.message) {
      this.showToast(link.params.message, 1500, 'top');
    } else if (link.type === 'page') {
      const pageParams = {
        pageId: link.target,
        params: link.params ? link.params : {},
        sessionId: localStorage.getItem('sessionId')
      };
      if (pageParams.params.skipWeb && pageParams.params.skipWeb.length > 0) {
        if (pageParams.params.title && pageParams.params.title.length > 0) {
          this.openUrl(pageParams.params.title, pageParams.params.skipWeb);
        } else {
          this.openUrl(title, pageParams.params.skipWeb);

        }
      } else {
        this.goToForward(pageParams);
      }
    } else if (link.type === 'chat' || link.type === 'pageModal' || link.type === 'modal' || link.type === 'model' || link.type === 'pageModalStyle') {
      this.eventService.emit('openPage', JSON.stringify(link));
    } else if (link.type === 'view') {
      const pageParams = {
        viewId: link.target,
        params: link.params ? link.params : {},
        sessionId: localStorage.getItem('sessionId')
      };
      this.goToForward(pageParams);
    } else if (link.type === 'url') {
      this.openUrl(title, link.target);
    }

  }


  async closeAlertAndPopoverAndModalAndMenu() {
    try {
      const alert = await this.alertCtrl.getTop();
      if (alert) {
        alert.dismiss();
        return;
      }
      const action = await this.actionSheetCtrl.getTop();
      if (action) {
        action.dismiss();
        return;
      }
      const popover = await this.popoverCtrl.getTop();
      if (popover) {
        popover.dismiss();
        return;
      }
      const modal = await this.modalController.getTop();
      if (modal) {
        modal.dismiss();
        return;
      }
      const isOpen = await this.menuCtrl.isOpen();
      if (isOpen) {
        this.menuCtrl.close();
        return;
      }
      // if (!this.tabsCanGoBack && !this.tabsParentCanGoBack) {
      //   // this.native.appMinimize();
      //   return;
      // }
    } catch (error) {
      console.log(new Date().toLocaleString() + '.' + new Date().getMilliseconds() + '  	close  closeAlertAndPopoverAndModalAndMenu  ', '');
    }
  }


  // 2024.05.29 蜂喔商户位于首页时
  checkBtnPressedAndShowMessage() {
    // 如果键盘是打开的，先关闭键盘
    // if (this.keyboard.isOpen()) {
    //   this.keyboard.close();
    //   return;
    // }

    this.closeAlertAndPopoverAndModalAndMenu();

    // 2024.01.12
    if (localStorage.getItem('platform') === 'ios') {
      return true;
    }
    // console.log("6666");
    if (this.backButtonPressed) {
      // 退出 App
      // this.platform.exitApp();
      // 最小化app
      // this.native.minimize();
      // 2.0安卓用于关闭应用
      if (typeof (cordova) !== 'undefined' && typeof (cordova.plugins.backgroundMode) !== 'undefined') {
        cordova.plugins.backgroundMode.moveToBackground();
      }
      // 关闭播放的声音
      // this.speaking.stopSpeak();
    } else {
      // 提示用户是否要关闭 app
      this.showToast("再按一次退出APP", 1500, "bottom");
      this.backButtonPressed = true;

      // 两秒内没有再按第二次，则将状态变为 false
      setTimeout(() => {
        this.backButtonPressed = false;
      }, 2000);
    }
  }

  // 显示关闭 App 提示框
  showExit() {
    // 2024.02.19 如果是预览项目，H5 则不处理提示 
    if (this.checkIsPreviewAndIsNotApp()) {
      return false;
    } else { // app
      if (this.getCurrentTarget()) {
        const params = this.getCurrentTarget();
        if (params.disableBack) {
          this.checkBtnPressedAndShowMessage();
          return true;
        }
      } else {
        // 当前位于tab1 -tab5
        this.checkBtnPressedAndShowMessage();
      }

      // 2024.05.29 
    }
    return false;
  }

  // 判断图片是否存在 有效返回true, 无效返回false
  isImgUrlValid(imgurl, callBackFunction) {
    return new Promise((resolve, reject) => {
      const ImgObj = new Image(); // 判断图片是否存在
      ImgObj.src = imgurl;
      ImgObj.onload = (res) => {
        // resolve(res);
        callBackFunction(true);
      };
      ImgObj.onerror = (err) => {
        // reject(err);
        callBackFunction(false);
      };
    }).catch((e) => { }); // 加上这句不会报错（Uncaught (in promise)）
  }



  /**
   *
   * clientType 铺铺旺 ppw 铺小旺 pxw  蜂喔 lj  蜂喔商户 js
   * eventName
   * enter_app_with_Event 统计进入app
   * enter_app_with_loginAccount_event 统计登录
   * enter_app_with_registerAccount_event 统计注册
   *
   */
  initUmengEventWithParameters(eventName: any) {
    /***********************铺小旺、铺铺旺********************************* */
    const umengPPWAndroidAppkey = '5e9680c0167edda9c30004e7';
    const umengPXWAndroidAppkey = '5eba40e00cafb2a2d100027e';
    const umengPPWAndroidChannel = 'android-channel';
    const umengPXWAndroidChannel = 'android-pxw-channel';
    const umengPPWIosAppkey = '5e968160167edddf0e000169';
    const umengPXWIosAppkey = '5eba4168570df3f9e900013d';
    const umengPPWIosChannel = 'ios-channel';
    const umengPXWIosChannel = 'ios-pxw-channel';
    /***********************蜂喔商户、蜂喔********************************* */
    const umengLJAndroidAppkey = '5fcf364fbed37e4506c608ff';
    const umengJSAndroidAppkey = '5fcf360519bda368eb4b112d';
    const umengLJAndroidChannel = 'android-lj-channel';
    const umengJSAndroidChannel = 'android-js-channel';
    const umengLJIosAppkey = '5fcf3b0f19bda368eb4b1513';
    const umengJSIosAppkey = '5fcf3abfbed37e4506c60b31';
    const umengLJIosChannel = 'ios-lj-channel';
    const umengJSIosChannel = 'ios-js-channel';
    try {

      if (window["Umeng"]) {
        if (localStorage.getItem("platform")
          && localStorage.getItem("platform") === 'ios'
          && localStorage.getItem("client") !== "BROWSER") {
          if (this.clientType === "pxw") {
            window["Umeng"].init(umengPXWIosAppkey, umengPXWIosChannel);
          } else if (this.clientType === "ppw") {
            window["Umeng"].init(umengPPWIosAppkey, umengPPWIosChannel);
          } else if (this.clientType === "lj") {
            window["Umeng"].init(umengLJIosAppkey, umengLJIosChannel);
          } else if (this.clientType === "js") {
            window["Umeng"].init(umengJSIosAppkey, umengJSIosChannel);
          }
        } else if (localStorage.getItem("platform")
          && localStorage.getItem("platform") === 'android'
          && localStorage.getItem("client") !== "BROWSER") {
          if (this.clientType === "pxw") {
            window["Umeng"].init(umengPXWAndroidAppkey, umengPXWAndroidChannel);
          } else if (this.clientType === 'ppw') {
            window["Umeng"].init(umengPPWAndroidAppkey, umengPPWAndroidChannel);
          } else if (this.clientType === 'lj') {
            window["Umeng"].init(umengLJAndroidAppkey, umengLJAndroidChannel);
          } else if (this.clientType === 'js') {
            window["Umeng"].init(umengJSAndroidAppkey, umengJSAndroidChannel);
          }
        }
        const eventData = {};
        if (localStorage.getItem("device")) {
          eventData["device"] = localStorage.getItem("device") + '_' + localStorage.getItem("userId");
        }
        if (localStorage.getItem("userId")) {
          eventData["userId"] = localStorage.getItem("userId");
        } else {
          eventData["userId"] = "guest";
        }
        window["Umeng"].onEventWithParameters(eventName, eventData);
      }
    } catch (error) {
      console.log("error-----> umeng error" + JSON.stringify(error));
    }
  }


  injectStyleToShadowRoot(renderer: Renderer2, element: HTMLElement, styleSheet: string): void {
    const style = renderer.createElement('style');
    style.innerHTML = styleSheet;
    element.shadowRoot.appendChild(style);
  }
  encryptDes(message) {
    var afterEncrypt = CryptoJS.DES.encrypt(message, CryptoJS.enc.Utf8.parse(secretKey), {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7
    }).toString()
    return afterEncrypt;
  }
  encryptALP(message) {
    var afterEncrypt = CryptoJS.DES.encrypt(message, CryptoJS.enc.Utf8.parse(sKey), {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7
    }).toString()
    return afterEncrypt;
  }
  decryptDes(message) {
    var afterDecrypt = CryptoJS.DES.decrypt(message, CryptoJS.enc.Utf8.parse(secretKey), {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7
    }).toString(CryptoJS.enc.Utf8);
    return afterDecrypt;
  }

  // 计算时间差
  handleDate(dateTimeStamp: Date) {
    let time = (dateTimeStamp.getTime())
    var minute = 1000 * 60;
    var hour = minute * 60;
    var day = hour * 24;
    var year = hour * 24 * 365;
    var result = '';
    var now = new Date().getTime();
    var diffValue = now - time;
    if (diffValue <= 0) {
      return result = "1年";
    } else {
      // todo 宜向上取整  Math.ceil(0.60); = Math.ceil(0.40); ≈ 1 
      return Math.ceil(diffValue / year) + '年';
    }

  }

  copyStr(e, str, msg) {
    if (e) {
      e.stopPropagation();
    }
    if (msg === undefined) {
      return;
    }
    this.copyString(str, msg);
  }

  copyString(str, msg?) {
    if (msg === undefined) {
      msg = "";
    }
    str = str.replaceAll(' ', '\r\n');

    if (this.platform.is('ios')) {
      
      if (window.isSecureContext) {
        navigator['clipboard'].writeText(str).then(() => {
          this.showToast('已复制' + msg, 2000, 'top');
        }).catch(err => {
          console.error('复制失败: ', err);
          this.showToast('复制失败', 2000, 'top');

        });
      } else {
        let result;
        const tempTextarea = document.createElement('textarea');
        document.body.appendChild(tempTextarea);
        tempTextarea.value = str;
        const u = navigator.userAgent;
        if (u.match(/(iPhone|iPod|iPad);?/i)) {
          window.getSelection().removeAllRanges();
          const range = document.createRange();
          range.selectNode(tempTextarea);
          window.getSelection().addRange(range);
          result = document.execCommand('copy');
          window.getSelection().removeAllRanges();
        }
        document.body.removeChild(tempTextarea);
        if (result) {
          this.showToast('已复制' + msg, 2000, 'top');
  
        } else {
          this.showToast('复制失败', 2000, 'top');
        }
      }
      

    } else {

      // 2024.05.13 vivo品牌的手机，荣耀手机不支持replaceAll函数 需要处理
      if (typeof (str.replaceAll) === 'function') {
        str = str.replaceAll(' ', '\r\n');
      } else {
        // 用于换行配置
        str = str.replace(' ', '\r\n');
      }

      let flag = false
      const save = (e) => {
        e.clipboardData.setData('text/plain', str);
        e.preventDefault();
      };
      document.addEventListener('copy', save);
      flag = document.execCommand('copy'); // 此处返回false导致安卓提示复制失败
      document.removeEventListener('copy', save);
      if (flag) {
        this.showToast('已复制' + msg, 2000, 'top');
      } else {
        this.showToast('复制失败', 2000, 'top');
      }
    }
  }
  jVerificationAuth(callBackFunction, newLoginPageData) {
    if ((typeof JGVerificationPlugin) === 'undefined') {
      callBackFunction(null);
      return;
    }
    // 当前网络环境不支持认证
    const that = this;
    JGVerificationPlugin.checkVerifyEnable(function (msg) {
      if (msg && msg === 'false') {
        console.log('msg------>当前网络环境不支持认证')
        callBackFunction('{}');
        return;
      } else {
        let otherLoginBtnStr;
        let wxLinkBtnStr;
        let isViewTypeDialog = false; // 是否是 弹窗模式
        let dialogHeight = 400; // 弹窗高度
        let slogan = '欢迎来到蜂喔'; // 欢迎广告语
        let isShowWxLinkBtn = false;
        if (newLoginPageData && newLoginPageData.data && newLoginPageData.data.button) {
          newLoginPageData.data.button.forEach(element => {
            if (element.type === 'otherLoginBtn') {
              otherLoginBtnStr = JSON.stringify(element.link);

              // 是否是 弹窗模式
              if (element.viewType !== undefined) {
                isViewTypeDialog = true;
              }

              // 欢迎广告语
              if (element.slogan !== undefined) {
                slogan = element.slogan;
              }

              // 弹窗高度
              if (element.dialogHeight) {
                dialogHeight = parseInt(element.dialogHeight);
              }

            } else if (element.type === 'wxlinkBtn') {
              isShowWxLinkBtn = true;
              wxLinkBtnStr = JSON.stringify(element.link);

            }
          });
        }

        var json = {
          //--------------------------IOS--------------------------------------
          // navCustom|BOOL|是否隐藏导航栏（适配全屏图片）
          // 授权页导航栏
          navColor: '16777215', // 授权页导航栏颜色
          navReturnImg: 'nav_icon_close', // 返回按钮图标名称
          navText: ['', '0', '0'], //String,int,int|导航栏标题[文字,文字颜色,文字大小]

          // 授权页logo
          logoHidden: true,//|BOOL|LOGO图片隐藏|
          // 授权页号码栏
          numberColor: '986895',
          numberSize: '36',

          // 授权页slogan
          sloganTextColor: '6710886',//隐藏LOGO
          sloganTextSize: '16',
          sloganOffsetY: '146',
          // 授权页登录按钮
          logBtnText: "本机号码一键登录",// 登录按钮文案
          logBtnImgs: ["0xFFE14A", "0xFFE14A", "0xFFCA3A"],// 登录按钮背景图片添加到数组(顺序如下) @[激活状态的图片,失效状态的图片,高亮状态的图片]
          logBtnHeight: '50', //按钮高度
          logBtnTextSize: '16',// 文字大小
          logBtnOffsetY: '270', // 登录按钮的marginTop 单位pt
          logBtnTextColor: '986895',
          // 授权页隐私栏
          appPrivacyColor: ['36095', '36095'], // IOS需要转成int |int,int|隐私条款名称颜色 @[基础文字颜色,条款颜色]|
          appPrivacyOne: ["《蜂喔用户协议》", "https://pay.fengwo168.com/staticH5/fengwoUserAgreement.html"],
          appPrivacyTwo: ["《蜂喔隐私权限》", "https://pay.fengwo168.com/staticH5/fengwo.html"],
          privacyLineSpacing: "6",
          // checkBox 复选框 
          checkedImg: 'checkBox_selected', // 复选框 选中协议的图片 |String|checkBox选中时图片|


          //-------------------------android-----------------------------------
          // 授权页导航栏
          setNavColor: '#FFFFFF', // 授权页导航栏颜色
          setNavReturnImgPath: 'nav_icon_close',// 左上角关闭按钮
          setNavText: '',// 不设置导航栏

          // 授权页logo
          setLogoHidden: true,//隐藏LOGO

          // 授权页号码栏
          setNumberColor: '#0F0F0F',
          setNumberSize: 36,
          setNumFieldOffsetY: 130,

          // 授权页slogan
          setSloganTextColor: '#666666',//隐藏LOGO
          setSloganTextSize: 16,
          // setSloganBottomOffsetY: 12,// 相对于屏幕底部下边缘Y轴偏移
          setSloganOffSetY: 174,

          // 授权页登录按钮
          setLogBtnText: "本机号码一键登录",// 登录按钮文案
          setLogBtnImgPath: "fw_login_btn_bg",// 登录按钮背景
          setLogBtnHeight: 50, //按钮高度
          setLogBtnTextSize: 16,// 文字大小
          setLogBtnOffsetY: 272, // 登录按钮的marginTop 单位sp ORGINAL
          setLogBtnTextColor: '#0F0F0F',// 按钮的问题颜色
          setLogBtnTextBold: true,// 本机号码意见登录加粗
          // 授权页隐私栏
          setPrivacyTopOffsetY: 400,
          // privacyState: true, 隐私条款check框默认状态 默认:NO
          // setLogBtnBottomOffsetY: 208,//服务协议距离底部屏幕的距离 ORGINAL
          setAppPrivacyColor: ['#008CFF', '#008CFF'],// 隐私权限文案颜色
          // setAppPrivacyOne: ["   《蜂喔用户协议》   ", "https://pay.fengwo168.com/staticH5/fengwoUserAgreement.html"],
          // setAppPrivacyTwo: ["   《蜂喔隐私权限》   ", "https://pay.fengwo168.com/staticH5/fengwo.html"],
          setCheckedImgPath: 'login_icon_checked', // 选中协议的图片

          // 授权页隐私协议web页面
          setPrivacyNavColor: '#FFFFFF',
          setPrivacyNameAndUrlBeanList: [" 蜂喔用户协议 ", "https://pay.fengwo168.com/staticH5/fengwoUserAgreement.html", "蜂喔隐私权限", "https://pay.fengwo168.com/staticH5/fengwo.html"],
          setPrivacyWithBookTitleMark: true,// 配置隐私条款运营商是否加书名号
          setPrivacyTextCenterGravity: true,// 文字左对齐
          setPrivacyOffsetX: 12,
          setPrivacyTextSize: 12, // 隐私协议字体大小
          setPrivacyCheckboxSize: 13,//checkbox尺寸
          setPrivacyState: false,// 默认选中
          setPrivacyNavReturnBtn: 'nav_icon_close',
          enableHintToast: [false, "请勾选用户协议！"]


          // 设置自定义view用于展示欢迎语句
          // setCustomView: ['欢迎来到蜂喔', '#0f0f0f'],

          // 设置其他手机号码登录
          // setSecondButton: ['其他手机号登录', '#999999', 'window["otherButton"]=' + otherLoginBtnStr + '']
        }
        if (isViewTypeDialog) {
          //-------------------------ios-----------------------------------

          json['numberSize'] = '32';
          json['showWindow'] = true;
          json['windowH'] = dialogHeight;
          json['welcomeTitleWindow'] = { label: slogan, color: '986895' }; // ['欢迎来到蜂喔', '#0f0f0f']
          json['secondButtonWindow'] = { label: '切换账号', color: '8421504', formatJs: 'window.pageModalService.setLink(' + otherLoginBtnStr + ')' };

          json['sloganOffsetY'] = '174';
          if (isShowWxLinkBtn) {
            json['wxLinkBtn'] = { label: '其他方式登录', color: '986895', formatJs: 'window.pageModalService.setWechatLink(' + wxLinkBtnStr + ')' };
          }
          //-------------------------android-----------------------------------

          // 授权页弹窗模式 setDialogTheme
          json['setDialogTheme'] = [window.innerWidth, dialogHeight, 0, 0, true];

          // 弹窗模式下  左上角按钮 参数 1.关闭按钮图标  2,距离顶部dp,3,距离左边dp
          json['setDialogCloseBtn'] = ["nav_icon_close", 20, 20];

          // 弹窗模式下 右上角切换账号按钮 参数 1.关闭按钮图标  2,文案 3,字体颜色,4,字体大小 5,距离顶部dp,6,距离右边dp 7,要执行的js
          json['setDialogSwitchBtn'] = ["nav_icon_switch", "切换账号", "#808080", 13, 22, 20, 'window["otherButton"]=' + otherLoginBtnStr + ''];

          // 隐私复选框 向上移动50dp
          json.setPrivacyTopOffsetY = 350;

          // 设置自定义view用于展示欢迎语句
          json['setCustomView1'] = [slogan, '#0f0f0f'];


          // 小屏幕 32
          json['setNumberSize'] = 32;


        } else {

          // 设置自定义view用于展示欢迎语句
          json['welcomeTitle'] = { label: slogan, color: '986895' }; // ['欢迎来到蜂喔', '#0f0f0f']

          // 设置其他手机号码登录
          json['secondButton'] = { label: '其他手机号登录', color: '986895', formatJs: 'window.pageModalService.setLink(' + otherLoginBtnStr + ')' };
          //-------------------------android-----------------------------------

          // 设置自定义view用于展示欢迎语句
          json['setCustomView'] = [slogan, '#0f0f0f'];

          // 设置其他手机号码登录
          json['setSecondButton'] = ['其他手机号登录', '#999999', 'window["otherButton"]=' + otherLoginBtnStr + ''];

          if (isShowWxLinkBtn) {
            // 设置其他方式登录 蜂喔用户2.1.0
            json['setWXLinkBtn'] = ["其他方式登录", "#B3B3B3", 'window["wxlinkButton"]=' + wxLinkBtnStr + ''];
            // ios 
            json['wxLinkBtn'] = { label: '其他方式登录', color: '986895', formatJs: 'window.pageModalService.setWechatLink(' + wxLinkBtnStr + ')' };
          }
        }
        if (that.platform.is('ios')) {
          JGVerificationPlugin.setCustomUIWithConfig(JSON.stringify(json));
        } else if (that.platform.is('android')) {
          JGVerificationPlugin.setCustomUIWithConfig(json);
        }

        JGVerificationPlugin.loginAuth(true, function (msg) {
          // alert(msg);
          callBackFunction(msg);
        });
      }
    });
  }
  // jVerificationAuth(callBackFunction, newLoginPageData) {
  //   if ((typeof JGVerificationPlugin) === 'undefined') {
  //     callBackFunction(null);
  //     return;
  //   }
  //   // 当前网络环境不支持认证
  //   JGVerificationPlugin.checkVerifyEnable(function (msg) {
  //     if (msg && msg === 'false') {
  //       console.log('msg------>当前网络环境不支持认证')
  //       callBackFunction(null);
  //       return;
  //     }
  //   })

  //   let otherLoginBtnStr;
  //   let wxLinkBtnStr;
  //   let isViewTypeDialog = false; // 是否是 弹窗模式
  //   let dialogHeight = 400; // 弹窗高度
  //   let slogan = '欢迎来到蜂喔'; // 欢迎广告语
  //   if (newLoginPageData && newLoginPageData.data && newLoginPageData.data.button) {
  //     newLoginPageData.data.button.forEach(element => {
  //       if (element.type === 'otherLoginBtn') {
  //         otherLoginBtnStr = JSON.stringify(element.link);

  //         // 是否是 弹窗模式
  //         if (element.viewType !== undefined) {
  //           isViewTypeDialog = true;
  //         }

  //         // 欢迎广告语
  //         if (element.slogan !== undefined) {
  //           slogan = element.slogan;
  //         }

  //         // 弹窗高度
  //         if (element.dialogHeight) {
  //           dialogHeight = parseInt(element.dialogHeight);
  //         }

  //       } else if (element.type === 'wxlinkBtn') {

  //         wxLinkBtnStr = JSON.stringify(element.link);
  //       }
  //     });
  //   }

  //   var json = {
  //     //--------------------------IOS--------------------------------------
  //     // navCustom|BOOL|是否隐藏导航栏（适配全屏图片）
  //     // 授权页导航栏
  //     navColor: '16777215', // 授权页导航栏颜色
  //     navReturnImg: 'nav_icon_close',
  //     navText: ['', '0', '0'], //String,int,int|导航栏标题[文字,文字颜色,文字大小]

  //     // 授权页logo
  //     logoHidden: true,//|BOOL|LOGO图片隐藏|
  //     // 授权页号码栏
  //     numberColor: '986895',
  //     numberSize: '36',

  //     // 授权页slogan
  //     sloganTextColor: '6710886',//隐藏LOGO
  //     sloganTextSize: '16',
  //     sloganOffsetY: '146',
  //     // 授权页登录按钮
  //     logBtnText: "本机号码一键登录",// 登录按钮文案
  //     logBtnImgs: ["0xFFE14A", "0xFFE14A", "0xFFCA3A"],// 登录按钮背景图片添加到数组(顺序如下) @[激活状态的图片,失效状态的图片,高亮状态的图片]
  //     logBtnHeight: '50', //按钮高度
  //     logBtnTextSize: '16',// 文字大小
  //     logBtnOffsetY: '270', // 登录按钮的marginTop 单位pt
  //     logBtnTextColor: '986895',
  //     // 授权页隐私栏
  //     appPrivacyColor: ['36095', '36095'], // IOS需要转成int |int,int|隐私条款名称颜色 @[基础文字颜色,条款颜色]|
  //     appPrivacyOne: ["《蜂喔用户协议》", "https://pay.fengwo168.com/staticH5/fengwoUserAgreement.html"],
  //     appPrivacyTwo: ["《蜂喔隐私权限》", "https://pay.fengwo168.com/staticH5/fengwo.html"],
  //     privacyLineSpacing: "6",
  //     // checkBox 复选框 
  //     checkedImg: 'checkBox_selected', // 复选框 选中协议的图片 |String|checkBox选中时图片|


  //     //-------------------------android-----------------------------------
  //     // 授权页导航栏
  //     setNavColor: '#FFFFFF', // 授权页导航栏颜色
  //     setNavReturnImgPath: 'nav_icon_close',// 左上角关闭按钮
  //     setNavText: '',// 不设置导航栏

  //     // 授权页logo
  //     setLogoHidden: true,//隐藏LOGO

  //     // 授权页号码栏
  //     setNumberColor: '#0F0F0F',
  //     setNumberSize: 36,
  //     setNumFieldOffsetY: 130,

  //     // 授权页slogan
  //     setSloganTextColor: '#666666',//隐藏LOGO
  //     setSloganTextSize: 16,
  //     // setSloganBottomOffsetY: 12,// 相对于屏幕底部下边缘Y轴偏移
  //     setSloganOffSetY: 174,

  //     // 授权页登录按钮
  //     setLogBtnText: "本机号码一键登录",// 登录按钮文案
  //     setLogBtnImgPath: "fw_login_btn_bg",// 登录按钮背景
  //     setLogBtnHeight: 50, //按钮高度
  //     setLogBtnTextSize: 16,// 文字大小
  //     setLogBtnOffsetY: 272, // 登录按钮的marginTop 单位sp ORGINAL
  //     setLogBtnTextColor: '#0F0F0F',// 按钮的问题颜色

  //     // 授权页隐私栏
  //     setPrivacyTopOffsetY: 400,
  //     // privacyState: true, 隐私条款check框默认状态 默认:NO
  //     // setLogBtnBottomOffsetY: 208,//服务协议距离底部屏幕的距离 ORGINAL
  //     setAppPrivacyColor: ['#008CFF', '#008CFF'],// 隐私权限文案颜色
  //     // setAppPrivacyOne: ["   《蜂喔用户协议》   ", "https://pay.fengwo168.com/staticH5/fengwoUserAgreement.html"],
  //     // setAppPrivacyTwo: ["   《蜂喔隐私权限》   ", "https://pay.fengwo168.com/staticH5/fengwo.html"],
  //     setCheckedImgPath: 'login_icon_checked', // 选中协议的图片

  //     // 授权页隐私协议web页面
  //     setPrivacyNavColor: '#FFFFFF',
  //     setPrivacyNameAndUrlBeanList: [" 蜂喔用户协议 ", "https://pay.fengwo168.com/staticH5/fengwoUserAgreement.html", "蜂喔隐私权限", "https://pay.fengwo168.com/staticH5/fengwo.html"],
  //     setPrivacyWithBookTitleMark: true,// 配置隐私条款运营商是否加书名号
  //     setPrivacyTextCenterGravity: true,// 文字左对齐
  //     setPrivacyOffsetX: 12,
  //     setPrivacyTextSize: 12, // 隐私协议字体大小
  //     setPrivacyCheckboxSize: 13,//checkbox尺寸
  //     setPrivacyState: false,// 默认选中
  //     setPrivacyNavReturnBtn: 'nav_icon_close',
  //     enableHintToast: [false, "请勾选用户协议！"]


  //     // 设置自定义view用于展示欢迎语句
  //     // setCustomView: ['欢迎来到蜂喔', '#0f0f0f'],

  //     // 设置其他手机号码登录
  //     // setSecondButton: ['其他手机号登录', '#999999', 'window["otherButton"]=' + otherLoginBtnStr + '']
  //   }

  //   if (isViewTypeDialog) {
  //     //-------------------------ios-----------------------------------

  //     json['numberSize'] = '32';
  //     json['showWindow'] = true;
  //     json['windowH'] = dialogHeight;
  //     json['welcomeTitleWindow'] = { label: slogan, color: '986895' }; // ['欢迎来到蜂喔', '#0f0f0f']
  //     json['secondButtonWindow'] = { label: '切换账号', color: '8421504', formatJs: 'window.pageModalService.setLink(' + otherLoginBtnStr + ')' };

  //   json['sloganOffsetY'] = '174';
  //   json['wxLinkBtn'] = { label: '其他方式登录', color: '986895', formatJs: 'window.pageModalService.setWechatLink(' + wxLinkBtnStr + ')' };
  //   //-------------------------android-----------------------------------

  //     // 授权页弹窗模式 setDialogTheme
  //     json['setDialogTheme'] = [window.innerWidth, dialogHeight, 0, 0, true];

  //     // 弹窗模式下  左上角按钮 参数 1.关闭按钮图标  2,距离顶部dp,3,距离左边dp
  //     json['setDialogCloseBtn'] = ["nav_icon_close", 20, 20];

  //     // 弹窗模式下 右上角切换账号按钮 参数 1.关闭按钮图标  2,文案 3,字体颜色,4,字体大小 5,距离顶部dp,6,距离右边dp 7,要执行的js
  //     json['setDialogSwitchBtn'] = ["nav_icon_switch", "切换账号", "#808080", 13, 22, 20, 'window["otherButton"]=' + otherLoginBtnStr + ''];

  //     // 隐私复选框 向上移动50dp
  //     json.setPrivacyTopOffsetY = 350;

  //     // 设置自定义view用于展示欢迎语句
  //     json['setCustomView1'] = [slogan, '#0f0f0f'];


  //     // 小屏幕 32
  //     json['setNumberSize'] = 32;


  //   } else {

  //     // 设置自定义view用于展示欢迎语句
  //     json['welcomeTitle'] = { label: slogan, color: '986895' }; // ['欢迎来到蜂喔', '#0f0f0f']

  //   // 设置其他手机号码登录
  //   json['secondButton'] = { label: '其他手机号登录', color: '986895', formatJs: 'window.pageModalService.setLink(' + otherLoginBtnStr + ')' };
  //   json['wxLinkBtn'] = { label: '其他方式登录', color: '986895', formatJs: 'window.pageModalService.setWechatLink(' + wxLinkBtnStr + ')' };




  //     //-------------------------android-----------------------------------

  //     // 设置自定义view用于展示欢迎语句
  //     json['setCustomView'] = [slogan, '#0f0f0f'];

  //     // 设置其他手机号码登录
  //     json['setSecondButton'] = ['其他手机号登录', '#999999', 'window["otherButton"]=' + otherLoginBtnStr + ''];

  //     // 设置其他方式登录 蜂喔用户2.1.0
  //     json['setWXLinkBtn'] = ["其他方式登录", "#B3B3B3", 'window["wxlinkButton"]=' + wxLinkBtnStr + ''];
  //   }
  //   if (this.platform.is('ios')) {
  //     JGVerificationPlugin.setCustomUIWithConfig(JSON.stringify(json));
  //   } else if (this.platform.is('android')) {
  //     JGVerificationPlugin.setCustomUIWithConfig(json);
  //   }

  //   JGVerificationPlugin.loginAuth(true, function (msg) {
  //     // alert(msg);
  //     callBackFunction(msg);
  //   });
  // }
  nextPage() {
    this.eventService.emit('NextPage', JSON.stringify(this.nextPageFomObj));
  }


  /**
  * 添加class
  */
  addClass(ele, value) {
    if (value) {
      let curValue = this.getClass(ele);
      if (curValue.indexOf(value) === -1) {
        curValue = curValue + " " + value;
      }
      ele.setAttribute("class", curValue.trim());
    }
  }
  /**
   * 删除class
   */
  removeClass(ele, value) {
    if (value) {
      let curValue = this.getClass(ele);
      if (curValue.indexOf(value) > -1) {
        curValue = (" " + curValue + " ").replace(" " + value + " ", " ");
      }
      ele.setAttribute("class", curValue.trim());
    }
  }
  /**
   * 元素是否存在值为@{value}的class
   */
  hasClass(ele, value) {
    let has = false;
    if (value) {
      const curValue = this.getClass(ele);
      if (curValue.indexOf(value) > -1) {
        has = true;
      }
    }
    return has;
  }

  /**
   * 获取class
   */
  getClass(elem) {
    return elem.getAttribute && elem.getAttribute("class") || "";
  }
  /**
   * 保存图片 到相册 downloadUrl base64 or http
   */
  saveImageFromUrl(downloadUrl, name) {
    const that = this;
    if (localStorage.getItem('client') === 'APP') {
      that.showToast('正在保存中...', 1500, 'top');
      that.base64ToGallery.base64ToGallery(downloadUrl, { prefix: name ? name : Date.now() + '', mediaScanner: true }).then(

        (res) => {
          console.log('Saved  image to gallery ', res);
          that.showToast('保存成功!', 1500, 'top');

        },
        err => {
          console.log('Error saving image to gallery ', err)
          that.showToast('保存出错了', 1500, 'top');
        }
      );

    } else {
      // base64
      if (downloadUrl.indexOf('data:image') > -1) {
        let a = document.createElement("a");
        // 新建点击事件
        let mouseEvent = new MouseEvent("click");
        // 将图片的 base64 编码，设置为 a标签的地址
        a.href = downloadUrl;
        a.setAttribute('download', Date.now() + '') // 设置属性
        // 触发点击事件
        a.dispatchEvent(mouseEvent);
      } else {
        // http 
        this.http.get(downloadUrl, { responseType: 'blob' }).subscribe((blob) => {

          const reader = new FileReader();
          reader.onloadend = () => {
            const downloadedImageStr = reader.result as string;

            let a = document.createElement("a");
            // 新建点击事件
            let mouseEvent = new MouseEvent("click");
            // 将图片的 base64 编码，设置为 a标签的地址
            a.href = downloadedImageStr;
            a.setAttribute('download', Date.now() + '') // 设置属性
            // 触发点击事件
            a.dispatchEvent(mouseEvent);
          };
          reader.readAsDataURL(blob);
        });
      }
    }
  }


  // //2023.12.02 获取字符串
  // getBase64Str(imgUrl, callBackFunction) {
  //   this.http.get(imgUrl, { responseType: 'blob' }).subscribe((blob) => {
  //     const reader = new FileReader();
  //     reader.onloadend = () => {
  //       const downloadedImageStr = reader.result as string;
  //       callBackFunction(downloadedImageStr);
  //     };
  //     reader.readAsDataURL(blob);
  //   });
  // }

  // 假设的getBase64Str方法，需要添加错误处理
  getBase64Str(url: string, callback: (str: string) => void, errorCallback?: (error: any) => void): void {
    // 模拟异步操作，例如使用fetch API获取图片Base64编码  
    fetch(url)
      .then(response => response.blob())
      .then(blob => {
        const reader = new FileReader();
        reader.onloadend = () => callback(reader.result as string);
        reader.readAsDataURL(blob);
      })
      .catch(error => {
        if (errorCallback !== null) {
          errorCallback(error);
        }
      });
  }



  getInterger(value) {
    return parseInt(value, 10);
  }

  showTipBox(type) {
    if (type === 1) {
      this.msgFirstTipObj.showBtnIcon = !this.msgFirstTipObj.showBtnIcon;
    } else if (type === 2) {
      this.msgSecondTipObj.showBtnIcon = !this.msgSecondTipObj.showBtnIcon;
    } else if (type === 3) { // 咨询管家

    }
  }

  showfloatShoppingCart(type) {
    if (type === false) {
      setTimeout(() => {
        this.floatShoppingCartIsShow = false;
      }, 10);
    } else if (type === true) {
      setTimeout(() => {
        this.floatShoppingCartIsShow = true;
      }, 10);
    }
  }

  dateAdd(interval, number, date) {
    /* 
      *   功能:实现DateAdd功能. 
      *   参数:interval,字符串表达式，表示要添加的时间间隔. 年 月 星期 日 
      *   参数:number,数值表达式，表示要添加的时间间隔的个数. 
      *   参数:date,时间对象. 
      *   返回:新的时间对象. 
      *   var   now   =   new   Date(); 
      *   var   newDate   =   dateAdd( "d ",5,now); 
      *---------------   dateAdd(interval,number,date)   ----------------- 
      */
    switch (interval) {
      case "y ": {
        date.setFullYear(date.getFullYear() + number);
        return date;
        break;
      }
      case "q ": {
        date.setMonth(date.getMonth() + number * 3);
        return date;
        break;
      }
      case "m ": {
        date.setMonth(date.getMonth() + number);
        return date;
        break;
      }
      case "w ": {
        date.setDate(date.getDate() + number * 7);
        return date;
        break;
      }
      case "d ": {
        date.setDate(date.getDate() + number);
        return date;
        break;
      }
      case "h ": {
        date.setHours(date.getHours() + number);
        return date;
        break;
      }
      case "m ": {
        date.setMinutes(date.getMinutes() + number);
        return date;
        break;
      }
      case "s ": {
        date.setSeconds(date.getSeconds() + number);
        return date;
        break;
      }
      default: {
        date.setDate(date.getDate() + number);
        return date;
        break;
      }
    }
  }

  /** 刷新当前页面 延时时间默认2s*/
  reloadCurrentPage(time?) {
    setTimeout(() => {
      this.eventService.eventEmit.emit('reloadCurrentPage', '1');
    }, time !== undefined ? time : 2000);
  }
  /** 刷新当前页面 默认设置刷新之前的页面*/
  reloadCurrentPageNeedRefreshPreviousPage(needRefresh = true, time?) {
    this.reloadCurrentPage(time);
    if (needRefresh) {
      setTimeout(() => {
        localStorage.setItem("needRefresh", "true");
      }, time !== undefined ? time : 2000);
    }
  }
  refreshPageData(res, needBack?, callbackFunc?: Function) {
    localStorage.removeItem('needRefresh'); // jason 7.28 移除 不再刷新更多页面
    if (res) {
      if (window['tabs']) {
        window['tabs'].getPageData(res, pageData => {
          if (needBack) {
            this.goBack();
          }
          setTimeout(() => {
            this.eventService.eventEmit.emit('refreshPageData' + localStorage.getItem('currentPath'), pageData);
            console.log('refreshPageData-eventEmit to --->' + localStorage.getItem('currentPath'));
          }, 500);
        });
      } else {
        console.error("window.tabs is null !");
        if (callbackFunc) callbackFunc('tabsIsNull');
      }

    }

  }


  refreshViewTree(content) {

    // 2024.06.21 fixed bug
    if (typeof (content.scrollByPoint) === 'function') {
      // 更新视图 用于刷新我的页面
      content.scrollByPoint(0, 1, 0);
      setTimeout(() => {
        content.scrollToTop();
      }, 200);
    }
  }

  getShellData(id) {
    if (this.shellData && this.shellData[id + localStorage.getItem('currentPath')]) {
      return this.shellData[id + localStorage.getItem('currentPath')];
    }
  }
  deleteShellData(id) {
    if (this.shellData && this.shellData[id + localStorage.getItem('currentPath')]) {
      delete this.shellData[id + localStorage.getItem('currentPath')];
    }
  }
  setShellData(data) {
    this.shellData[data.shellDataId + localStorage.getItem('currentPath')] = data;

  }
  toShellData(res, forNgTabs?, params?) {
    //  判断当前page、part 是否已撤销缓存机制
    if (res.isShell != undefined && res.isShell === false) {
      // 撤销缓存 删除缓存
      if (params && params.pageId) {
        this.deleteCacheByKeyCallback(params.pageId, res => {
          console.log('配置取消缓存，删除本地缓存pageId: ' + params.pageId);
        })
      } else if (params && params.viewId) {
        this.deleteCacheByKeyCallback(params.viewId, res => {
          console.log('配置取消缓存，删除本地缓存viewId: ' + params.viewId);
        })
      }
    }



    //2024.01.11 解析购物车数量
    const titleBar =
      (JSON.stringify(res.titleBar) !== undefined && JSON.stringify(res.titleBar) !== '{}') ? res.titleBar : undefined;

    // 1.6.29 numberOfCart
    if (titleBar && titleBar.cart && titleBar.cart.count !== undefined) {
      if (titleBar.cart.link && titleBar.cart.link.params && titleBar.cart.link.params.useCartNumber) {
        window['chatService'].setCartItemCount(titleBar.cart.count, true);
      }
    }

    const tags = res.views === undefined ? res.tags : res.views[0].tags;
    if (tags && tags.length > 0) {
      tags.forEach(element => {
        if (element.shellDataId && element.shellDataId !== "0") {
          this.setShellData(element);
          if (!this.getShellData(element.shellDataId)) {// && element.remove !== "true"
            // this.setShellData(element);
          }
        }
      });
      if (forNgTabs) {
        this.eventService.eventEmit.emit("updateTabsCurrentDataTags" + localStorage.getItem('currentPath'), JSON.stringify(tags))

      }
      // update page tags    xx xx
      this.eventService.eventEmit.emit("updateTagsData" + localStorage.getItem('currentPath'), "1")
      this.eventService.eventEmit.emit("updateTagsDataFooter" + localStorage.getItem('currentPath'), "1")
      this.eventService.eventEmit.emit("updateTagsDataHeader" + localStorage.getItem('currentPath'), "1")
      this.eventService.eventEmit.emit("updateTagsDataNav1" + localStorage.getItem('currentPath'), "1")
      this.eventService.eventEmit.emit("updateTagsDataSub1" + localStorage.getItem('currentPath'), "1")
      this.eventService.eventEmit.emit("updateTagsDataNav2" + localStorage.getItem('currentPath'), "1")
      this.eventService.eventEmit.emit("updateTagsDataTab1" + localStorage.getItem('currentPath'), "1")
      this.eventService.eventEmit.emit("updateTagsDataTab2" + localStorage.getItem('currentPath'), "1")
      this.eventService.eventEmit.emit("updateTagsDataTab3" + localStorage.getItem('currentPath'), "1")
      this.eventService.eventEmit.emit("updateTagsDataTab4" + localStorage.getItem('currentPath'), "1")
      this.eventService.eventEmit.emit("updateTagsDataTab5" + localStorage.getItem('currentPath'), "1")

    }

  }
  initCacheDb() {
    try {
      const dbName = 'cacheData';
      const dbVersion = 1;

      const indexedDB = window.indexedDB;
      const openReq = indexedDB.open(dbName, dbVersion);
      // 处理数据库打开成功或失败的事件
      openReq.onerror = (event) => {
        console.error("cacheData error:", event);
      };

      openReq.onsuccess = (event) => {
        this.db = event.target['result'];
        console.log("cacheData opened successfully!", this.db);
      };

      openReq.onupgradeneeded = (event) => {
        this.db = event.target['result'];
        // 在这里可以创建对象存储空间或索引等

        const objectStore = this.db.createObjectStore('cache', { keyPath: 'id' });

      };
    } catch (error) {
      console.log('initCacheDb-----> error:' + JSON.stringify(error));
    }
  }
  getCacheByKey(key, callbackFunc: Function) {
    try {
      const transaction = this.db.transaction(['cache'], "readonly");
      const store = transaction.objectStore('cache');
      const obj = store.get(key);
      if (obj) {
        obj.onsuccess = (event) => {
          if (obj.result) {
            callbackFunc(obj.result);
          } else {
            callbackFunc("-1");
          }
        }
      } else {
        callbackFunc("-1");
      }

    } catch (error) {
      callbackFunc("-1");
      console.log('getCacheByKey-----> error:' + JSON.stringify(error));
    }

  }
  // add data
  addCacheCallback(content, callbackFunc: Function) {
    try {
      const transaction = this.db.transaction(['cache'], "readwrite");
      const store = transaction.objectStore('cache');
      const req = store.add(content);
      req.onerror = (e) => console.log("Error", e.target.error.name + '|' + 'cache');
      req.onsuccess = (e) => { callbackFunc(); console.log("cache save complete callbak "); };
    } catch (error) {
      console.log('addCacheCallbak-----> error:' + JSON.stringify(error));
    }

  }

  putCacheCallback(content, callbackFunc: Function) {
    try {
      const transaction = this.db.transaction(['cache'], "readwrite");
      const store = transaction.objectStore('cache');
      const req = store.put(content);
      req.onerror = (e) => console.log("Error", e.target.error.name + '|' + 'cache');
      req.onsuccess = (e) => { callbackFunc(); console.log("cache update complete callbak"); };
    } catch (error) {
      console.log('msg-----> error:' + JSON.stringify(error));
    }

  }
  deleteCacheByKeyCallback(key, callbackFunc: Function) {
    try {
      const transaction = this.db.transaction(['cache'], "readwrite");
      const store = transaction.objectStore('cache');
      const req = store.delete(key);
      req.onerror = (e) => console.log("Error", e.target.error.name + '|' + 'cache');
      req.onsuccess = (e) => { callbackFunc(); console.log("cache delete complete"); };
    } catch (error) {
      console.log('msg-----> error:' + JSON.stringify(error));
    }
  }

  clearALLCacheData(storeName, callbackFunc?: Function) {
    // localStorage.clear();
    try {
      const transaction = this.db.transaction([storeName], "readwrite");
      const objectStore = transaction.objectStore([storeName]);
      const result = objectStore.clear();
      console.log('msg-----> clearALLCacheData:' + JSON.stringify(result));
      callbackFunc(result);
    } catch (errror) {
      callbackFunc('-1');

    }
  }

  async getObjectStoreSize(callbackFunc?: Function) {
    const transaction = this.db.transaction('cache', 'readonly');
    const store = transaction.objectStore('cache');

    let size = 0;
    const that = this;
    const cursorRequest = await store.openCursor();
    cursorRequest.onsuccess = async (event) => {
      const cursor = event.target.result;
      if (cursor) {
        const value = cursor.value;
        const jsonValue = JSON.stringify(value);
        size += new TextEncoder().encode(jsonValue).length;
        cursor.continue();
      } else {
        console.log('Cache size in bytes:', size);
        callbackFunc(that.formatSize(size));
      }
    };

    cursorRequest.onerror = function (event) {
      console.error('Error getting cursor:', event.target.error);
      callbackFunc(that.formatSize(size));
    };
  }
  formatSize(sizeInBytes) {
    const KB = 1024;
    const MB = KB * 1024;

    if (sizeInBytes >= MB) {
      return (sizeInBytes / MB).toFixed(2) + ' MB';
    } else if (sizeInBytes >= KB) {
      return (sizeInBytes / KB).toFixed(2) + ' KB';
    } else {
      return sizeInBytes + ' B';
    }
  }
  goBack(pages?: number) {
    this.saveFormData();
    if (pages && Math.abs(pages) !== 1) {
      window.history.go(pages) // 返回多级页面暂时没办法使用navCtrl
    } else {
      this.nav.back();
      // // 2.2.3 fixed bug 登录跳转到successPage之后只有登录状态才进入
      // if (localStorage.getItem('loginStatus') && localStorage.getItem('loginStatus')==='true' && this.getCurrentTarget() === null && localStorage.getItem('tabPath')) {
      //   this.router.navigate([localStorage.getItem('tabPath')], { queryParams: {}, replaceUrl: true });
      // } else {
      //   this.nav.pop();
      // }
    }
    
  }

  initData() {
    this.defaultCityCenter = { lng: 114.06450485520935, lat: 22.549179943799096 }; // 北京中心点 { lng: 116.402544, lat: 39.908958 };

    this.alertDivTotalCount = {
      plugin_id1: 0,
      plugin_id2: 0,
      plugin_id3: 0,
      plugin_id4: 0,
      plugin_id5: 0,
      plugin_id6: 0,
      plugin_id7: 0,
      plugin_id8: 0,
      plugin_id9: 0,
      plugin_id10: 0,
      plugin_id11: 0,
      plugin_id12: 0,
      plugin_id13: 0,
      plugin_id14: 0,
      plugin_id15: 0,
      plugin_id16: 0,
      plugin_id17: 0,
      plugin_id18: 0,
      plugin_id19: 0,
      plugin_id20: 0,
      plugin_id21: 0,
      plugin_id22: 0,
      plugin_id23: 0,
      plugin_id24: 0,
      plugin_id25: 0,
      plugin_id26: 0,
      plugin_id27: 0,
      plugin_id28: 0,
      plugin_id29: 0,
      plugin_id30: 0,
      plugin_id31: 0,
      plugin_id32: 0,
      plugin_id33: 0,
      plugin_id34: 0,
      plugin_id35: 0,
      plugin_id36: 0,
      plugin_id37: 0,
      plugin_id38: 0,
      plugin_id100: 0,
    };


    this.tipsTotalCount = {
      plugin_id1: 0,
      plugin_id2: 0,
      plugin_id3: 0,
      plugin_id4: 0,
      plugin_id5: 0,
      plugin_id6: 0,
      plugin_id7: 0,
      plugin_id8: 0,
      plugin_id9: 0,
      plugin_id10: 0,
      plugin_id11: 0,
      plugin_id12: 0,
      plugin_id13: 0,
      plugin_id14: 0,
      plugin_id15: 0,
      plugin_id16: 0,
      plugin_id17: 0,
      plugin_id18: 0,
      plugin_id19: 0,
      plugin_id20: 0,
      plugin_id21: 0,
      plugin_id22: 0,
      plugin_id23: 0,
      plugin_id24: 0,
      plugin_id25: 0,
      plugin_id26: 0,
      plugin_id27: 0,
      plugin_id28: 0,
      plugin_id29: 0,
      plugin_id30: 0,
      plugin_id31: 0,
      plugin_id32: 0,
      plugin_id33: 0,
      plugin_id34: 0,
      plugin_id35: 0,
      plugin_id36: 0,
      plugin_id37: 0,
      plugin_id38: 0,
      plugin_id100: 0,
    };

    this.visitorMsg = {
      datetime: Date.now(),
      msg: {
        from: "",
        message: "",
        tel: "",
        type: "general"
      }
    };// 是否为访客



    // 服务中心新增按钮
    this.msgTopTipButtonObj = {
      visible: false,
      showBtnIcon: true,
      closeIcon: 'https://zeno-img.oss-cn-shenzhen.aliyuncs.com/file_168869863682848ccef20f724914e93321c4fbf53156b.png',
      secondRowLabel: '',
      secondRowLabelCssStyle: '',
      tipsMainBoxCssStyle: '',
      buttonLabel: '',
      buttonLabelCssStyle: '',
      buttonLink: {}
    };


    this.floatShoppingCartObj = {
      icon: "",
      count: 0,
      iconCssStyle: "",
      countCssStyle: "",
      buttonLink: {
        link: {

        },
      },
    };
    this.loginRes = {
      success: true,
      sessionId: localStorage.getItem("sessionId"),
      id: null,
      type: "page",
      target: "0",
      params: {
        user_id: "",
        position: {
          code: 4403, name: "深圳"
        },
        account: "",
        way: "2",
        pageName2: ":page_name",
        useToTarget: "1",
        eventPosition: "after"
      },
      message: "登录成功！",
      data:
      {
        user_id: "",
        position: { code: 4403, name: "深圳" },
        eventResult: "true",
        account: ""
      },
      code: 200, skip: 0, refreshCache: false
    };
    this.resetMessageData();
  }
  resetMessageData() {
    this.msgFirstTipObj = {
      visible: false,
      showBtnIcon: true,
      closeIcon: 'https://zeno-img.oss-cn-shenzhen.aliyuncs.com/file_167704994061487b3b1695682303aa8728a8888edda24.png',
      closeIconCssStyle: '',
      topFirstRowLeftIcon: '',
      topFirstRowLeftIconCssStyle: '',
      tipsMainBoxCssStyle: '',
      topFirstRowLabel: '',
      topFirstRowLabelCssStyle: '',
      secondRowLabel: '',
      secondRowLabelCssStyle: '',
      buttonLabel: '',
      buttonLabelCssStyle: '',
      buttonLink: {}
    };
    this.msgSecondTipObj = {
      visible: false,
      showBtnIcon: true,
      closeIcon: 'https://zeno-img.oss-cn-shenzhen.aliyuncs.com/file_167704994061487b3b1695682303aa8728a8888edda24.png',
      closeIconCssStyle: '',
      topFirstRowLeftIcon: '',
      topFirstRowLeftIconCssStyle: '',
      topFirstRowLabel: '',
      topFirstRowLabelCssStyle: '',
      secondRowLabel: '',
      secondRowLabelCssStyle: '',
      secondRowLabel2: '',
      secondRowLabel2CssStyle: '',
      buttonLabel: '',
      buttonLabelCssStyle: '',
      buttonLink: {}
    };
  }
  //计算对象数组中某个属性合计
  countTotal = (arr, keyName) => {
    let total = "";
    total = arr.reduce(function (total, currentValue, currentIndex, arr) {
      return currentValue[keyName] ? (total + currentValue[keyName]) : total;
    }, "");
    return total;
  }

  // 是否是手机APP
  isMobileApp() {
    return ((this.platform.is('android') && localStorage.getItem('client') !== 'BROWSER')
      || (this.platform.is('ios') && localStorage.getItem('client') !== 'BROWSER'));

  }

  formatTimestamp(timestamp) {
    let validTimestamp;
    timestamp += '';

    // 尝试去除可能的非数字字符，并转换为数字  
    const cleanedTimestamp = timestamp.replace(/[^\d]/g, '');
    validTimestamp = Number(cleanedTimestamp);

    // 如果字符串完全由数字组成，但没有毫秒单位（比如是一个秒级时间戳），则乘以1000  
    if (!isNaN(validTimestamp) && validTimestamp < 1e10) { // 假设Unix时间戳至少为10位数  
      validTimestamp *= 1000;
    }

    return validTimestamp;
  }


  fontFunAddOne(a) {
    return a + 1;
  }

  consoleLog(msg, obj?) {
    if (!this.disableConsoleLog) {
      if (obj !== undefined) {
        console.log(`${new Date().toLocaleString()}.${new Date().getMilliseconds()} ` + msg, obj);
      } else {
        console.log(`${new Date().toLocaleString()}.${new Date().getMilliseconds()} `, msg);
      }
    }
  }

  // 获取好友的头像  如果不存在则调用接口取出来



  // // 获取头像，如果不存在则调用接口取出  
  // getAvatar(userId: string, url?: string): Promise<string | undefined> {
  //   if (this.avatars[userId]) {
  //     return Promise.resolve(this.avatars[userId]);
  //   } else {
  //     return new Promise((resolve, reject) => {
  //       this.getBase64Str(url + "?x-oss-process=image/resize,h_36", (str) => {
  //         this.setAvatar(userId, str);
  //         resolve(str);
  //       }, reject);
  //     });
  //   }
  // }

  qqMapTransBMap(lng, lat) { // 腾讯/高德地图经纬度转换成百度经纬度：
    let x_pi = 3.14159265358979324 * 3000.0 / 180.0;
    let x = lng;
    let y = lat;
    let z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
    let theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
    let lngs = z * Math.cos(theta) + 0.0065;
    let lats = z * Math.sin(theta) + 0.006;
    return { lng: lngs, lat: lats };
  }


  bMapTransQQMap(lng, lat) { // 百度经纬度转换成腾讯/高德地图经纬度：
    let x_pi = 3.14159265358979324 * 3000.0 / 180.0;
    let x = lng - 0.0065;
    let y = lat - 0.006;
    let z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
    let theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
    let lngs = z * Math.cos(theta);
    let lats = z * Math.sin(theta);
    return { lng: lngs, lat: lats };
  }

  // 登录或者退出登录初始化临时全局变量
  initTemporaryVariables() {
    let that = this;
    that.locationAddressLabel = ''; // 选择收货地址临时变量
    that.getAddressLat = that.defaultCityCenter.lat; // 纬度
    that.getAddressLng = that.defaultCityCenter.lng; // 经度
    that.addressEventResultValue = ''; // 选择地址接收事件返回eventResult
    that.addressEventResultName = '';  // 选择地址接收事件返回名称
    that.needCheckTabName = '';// 用户切换选项卡记录
    that.searchShopLat = that.defaultCityCenter.lat;// 用户搜索店铺纬度
    that.searchShopLng = that.defaultCityCenter.lng;// 用户搜索店铺经度
    that.shopAddressSelectItemLocation = '';// 用户选择地址具体地址信息
    that.shopAddressSelectItemPhone = '';// 用户选择手机号码
    that.shopAddressSelectItemName = '';// 用户选择名称
    localStorage.removeItem('smoothIndexRecommendTab');// 2.2.16 跳转到商铺首页新增参数
    localStorage.removeItem('chatCustomBtnLink');// 2.2.16 2.3.5 删除点击活动按钮跳转自定义弹窗link
    // 2024.08.05 初始化好友列表
    that.eventService.eventEmit.emit('clearMyFriendList', 1);
    that.addedMessages = new Set();
    localStorage.removeItem('recevieMsgLastTime');
    that.addedFormatTimes = new Set();
  }



  // 2024.10.16
  debounce(func: Function, wait: number): Function {
    let timeout: any;
    return function (...args: any[]) {
      const context = this;
      clearTimeout(timeout);
      timeout = setTimeout(() => func.apply(context, args), wait);
    };
  }



  sendShareUserIdToWx() {
    setTimeout(() => {
      if (localStorage.getItem('userId') && localStorage.getItem('userId').length > 0) {

        if ((typeof wx) !== 'undefined') {
          wx.miniProgram.getEnv((res) => {
            if (res.miniprogram) {
              let path = '/pages/session/session?shareUser=' + encodeURIComponent(localStorage.getItem('userId'))

              wx.miniProgram.navigateTo({ url: path });
            }
          });
        }
      }
    }, 200);

  }
  // 2024.11.08 
  getUrlParamsByName(url, paramsName) {
    let result = '';
    const currentUrl = url;
    const hashIndex = currentUrl.indexOf('#');
    if (hashIndex !== -1) {
      // 获取哈希值之后的部分，包括查询字符串
      const hashPart = currentUrl.slice(hashIndex + 1);

      // 查找查询字符串的开始位置（即'?'的位置）
      const queryStringIndex = hashPart.indexOf('?');
      if (queryStringIndex !== -1) {
        // 提取查询字符串部分
        const queryString = hashPart.slice(queryStringIndex);

        // 使用URLSearchParams来解析查询字符串
        const params = new URLSearchParams(queryString);

        // 获取指定参数的值
        const customNameValue = params.get(paramsName);

        // 输出结果
        // console.log('sharer_user:', customNameValue);

        result = customNameValue;
      }
    } else {
      this.consoleLog('URL中没有找到哈希值（#）。', '  	   ');
    }
    return result;
  }
// 退出发布时保存草稿
  saveFormData(action?){
    if(this.coms && this.coms.length > 0 && this.pageId!=""){
      this.coms.forEach(element => {
        const style = element.tagData.style;
        if(style === 'tag.AppGeneralFormTagLogic'){
          // 表单第一个配置 formType = "saveDraft" value = "true" 存稿
          if(element && element.tagData && element.tagData.data && element.tagData.data.htmlObj && element.tagData.data.htmlObj[0].formType === 'saveDraft' && element.tagData.data.htmlObj[0].value === 'true' ){
            // 以pageId为key存储
            localStorage.setItem("saveDraft:"+this.pageId,JSON.stringify(
              { "htmlObj":element.tagData.data.htmlObj ,
                "formValue":this.getFormGroupWithParamName(element.tagData.paramName).value,
                "time": new Date().getTime()
              }) )   
              if (action == 1) {
                this.showToast('已存草稿~',1500,'middle');
              }
          }
        }

      })       
    }
  }
  // 提交成功 删除草稿
  delFormData(){
    if(localStorage.getItem("saveDraft:"+this.pageId)){
      localStorage.removeItem("saveDraft:"+this.pageId)
    }
  }

   // 添加水印的函数
   addWatermark(sourceImage, watermarkImage, callback, sourceW?,sourceH?, watermarkW?, watermarkH?,watermarkX?,watermarkY?) {
    const image = new Image();
    image.src = sourceImage;
    image.onload = () => {
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
      canvas.width = sourceW ? sourceW : 330 * 2; // image.width;
      canvas.height = sourceH ? sourceH : 208 * 2; // image.height;

      // 绘制原图
      ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
      // 加载水印图片
      const watermark = new Image();
      watermark.width = watermarkW ? watermarkW : 88 * 2;
      watermark.height = watermarkH ? watermarkH : 88 * 2;
      watermark.src = watermarkImage;
      watermark.onload = () => {
        if (watermarkX && watermarkY) {
            // 绘制水印图片（改变位置）
            ctx.drawImage(watermark, watermarkX, watermarkY, watermarkW, watermarkH);
        } else {
          // 绘制水印图片（这里默认在右下角）
          ctx.drawImage(watermark, canvas.width - watermark.width - 16, canvas.height - watermark.height - 16, watermark.width, watermark.height);
        }
        
        // 回调处理后的图片数据
        callback(canvas.toDataURL('image/png'));
      };
    };
  }
}


